<?php
/**
*
* 功能描述（代金数据）
*
* @author suoya <jlusuoya@gmail.com>
* @version 1
*/

class ModelVoucher extends ModelBase
{
	public $key_eq = array(
		'user_id' => true,
		'adm_id' => true,
		'prefix' => true,
	);		//精确搜索关键字
	public $key_cover = array(
		'u_start' => 'usetime >=',
		'u_end' => 'usetime <=',
		'prefix' => 'left(`no`, 6)',
	);	//转换搜索关键字
	function Create($prefix, $amount, $cnt, $outtime, $admid)
	{
		$do_cnt = 0;
		$fail = 0;
		do {
			$no_arr = CreateNo($prefix, 6);
			foreach($no_arr as $item)
			{
				$data = array(
					'no' => $item,
					'adm_id' => $admid,
					'amount' =>$amount,
					'outtime' => $outtime, 
				);
				$id = $this->db->insert('voucher', $data);
				if($id > 0)
				{
					$do_cnt++;
					if($do_cnt >= $cnt)
						return $cnt;
				}
				{
					$fail++;
					if($fail >= $cnt)
						return $do_cnt;
				}
			}
		}while(true);
		return 0;
	}

	function GetList(&$search, &$pageinfo, $fild)
	{
		$where = get_where($this, $search);
		$data  = $this->db->getRow("voucher", 'count(1) cnt', $where);
		if($data['cnt'] == 0)
		{
			$this->DealPage($pageinfo, 0);
			return array();
		}
		if($fild == null)
		{
			$fild = '`id`, `status`, `no`, `createtime`, `outtime`, `usetime`, `amount`, `amount_use`, `user_id`, `adm_id`, `order_id`';
			$limit = $this->DealPage($pageinfo, $data['cnt']);
		}
		else
			$limit = '';
		$data = $this->db->GetAll('voucher', $fild, $where, '', $limit);
		return $data;
	}

	function GetBaseList(&$search, &$pageinfo, &$head)
	{
		$head = array('序列号', '金额', '过期时间', '状态:1新生成2已导出3已发放4已使用5已过期');
		return $this->GetList($search, $pageinfo, '`no`, `amount`, `outtime`, `status`');
	}

	function SetExport(&$search)
	{
		$where = get_where($this, $search);
		$data = $this->db->Update('voucher', array('status'=>2), $where . ' and status = 1');
		return $data;
	}

	function SetOpen(&$search)
	{
		$where = get_where($this, $search);
		$data = $this->db->Update('voucher', array('status'=>3), $where . ' and status < 3');
		return $data;
	}
}

